package kn.pulldata.common;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 类描述：全局异常拦截
 *
 * @author XJW
 * @since 2025/7/8 16:33
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleValidationException(MethodArgumentNotValidException ex) {
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();

        // 提取所有字段错误信息
        StringBuilder message = new StringBuilder();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append("：").append(error.getDefaultMessage()).append("; ");
        }

        // 返回自定义响应体
        return AjaxResult.error("参数校验失败：" + message.toString());
    }

    /**
     * 控制器参数绑定错误（如类型转换失败等）
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(BindException ex) {
        StringBuilder message = new StringBuilder();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            message.append(error.getField()).append("：").append(error.getDefaultMessage()).append("; ");
        }
        return AjaxResult.error("参数绑定失败：" + message.toString());
    }

    /**
     * 请求体参数错误（JSON格式不对、类型转换失败等）
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public AjaxResult handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        return AjaxResult.error("请求体格式错误：" + ex.getLocalizedMessage());
    }


    /**
     * 空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public AjaxResult handleNullPointerException(NullPointerException ex) {
        return AjaxResult.error("空指针异常：" + ex.getMessage());
    }

    /**
     * 非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public AjaxResult handleIllegalArgumentException(IllegalArgumentException ex) {
        return AjaxResult.error("非法参数：" + ex.getMessage());
    }

    /**
     * 运行时异常捕获（RuntimeException）
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException ex) {

        return AjaxResult.error("系统运行时异常：" + ex.getMessage());
    }
    /**
     * 所有未捕获的异常（兜底）
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception ex) {
        return AjaxResult.error("系统内部异常：" + ex.getMessage());
    }
}
